<template>
	<div class="home-container">
		<!-- 筛选区域和统计卡片 -->
		<div class="filter-section">
			<div class="filter-group">
				<el-select v-model="filterForm.year" placeholder="年度" @change="handleFilterChange" class="filter-select">
					<el-option
						v-for="year in yearOptions"
						:key="year"
						:label="`${year}年`"
						:value="year"
					/>
				</el-select>
				<span class="filter-separator">/</span>
				<el-select v-model="filterForm.month" placeholder="月度" @change="handleFilterChange" class="filter-select">
					<el-option
						v-for="month in monthOptions"
						:key="month.value"
						:label="month.label"
						:value="month.value"
					/>
				</el-select>
				<el-date-picker
					v-model="filterForm.dateRange"
					type="daterange"
					range-separator="至"
					start-placeholder="起始日期"
					end-placeholder="结束日期"
					:shortcuts="dateShortcuts"
					:unlink-panels="true"
					@change="handleFilterChange"
					@visible-change="onDateVisibleChange"
					class="filter-select"
				/>
				<el-select v-model="filterForm.documentType" placeholder="单据类型" @change="handleFilterChange" class="filter-select">
					<el-option
						v-for="type in documentTypeOptions"
						:key="type.value"
						:label="type.label"
						:value="type.value"
					/>
				</el-select>
						</div>
			
			<!-- 统计卡片 -->
			<div class="stats-section">
				<div class="stat-card">
					<div class="stat-icon" style="background: rgba(0, 122, 255, 0.12);">
						<el-icon size="24" style="color: #007aff;">
							<Document />
						</el-icon>
						</div>
					<div class="stat-content">
						<div class="stat-value">{{ statistics.totalCount.toLocaleString() }}</div>
						<div class="stat-label">单据总量</div>
					</div>
				</div>
				<div class="stat-card">
					<div class="stat-icon" style="background: rgba(52, 199, 89, 0.12);">
						<el-icon size="24" style="color: #34c759;">
							<Check />
						</el-icon>
				</div>
					<div class="stat-content">
						<div class="stat-value">{{ statistics.passedCount.toLocaleString() }}</div>
						<div class="stat-label">智能制证量</div>
									</div>
								</div>
							</div>
						</div>

		<!-- 图表区域 -->
		<div class="chart-section">
			<div class="chart-header">
				<h3>数据趋势</h3>
				</div>
			<div class="chart-container">
				<div ref="chartRef" class="chart" v-loading="loading"></div>
			</div>
				</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { Document, Check } from '@element-plus/icons-vue';
import { useHistoryDataApi } from '/@/api/historyData';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useUserInfo } from '/@/stores/userInfo';

const { themeConfig } = storeToRefs(useThemeConfig());
const { userInfos } = storeToRefs(useUserInfo());
const historyDataApi = useHistoryDataApi();

// 获取当前用户部门
const currentDeptName = computed(() => userInfos.value.dept_info?.dept_name || '');

// 根据部门设置允许的单据类型
const allowedDocumentTypes = computed(() => {
	const deptName = currentDeptName.value;
	if (deptName === '核算部') {
		return ['BX', 'CJ', 'CL', 'CX', 'GJ', 'KK', 'RZ', 'SK', 'XJ', 'ZZ'];
	} else if (deptName === '税务部') {
		return ['SJ', 'ZD', 'JF'];
	}
	// 其他部门或管理员，不限制
	return null;
});

// 所有单据类型选项
const allDocumentTypeOptions = [
	{ label: '全部', value: 'all' },
	{ label: 'BX', value: 'BX' },
	{ label: 'CJ', value: 'CJ' },
	{ label: 'CL', value: 'CL' },
	{ label: 'CX', value: 'CX' },
	{ label: 'GJ', value: 'GJ' },
	{ label: 'JF', value: 'JF' },
	{ label: 'KK', value: 'KK' },
	{ label: 'RZ', value: 'RZ' },
	{ label: 'SJ', value: 'SJ' },
	{ label: 'SK', value: 'SK' },
	{ label: 'XJ', value: 'XJ' },
	{ label: 'ZD', value: 'ZD' },
	{ label: 'ZZ', value: 'ZZ' }
];

// 根据部门权限过滤单据类型选项
const documentTypeOptions = computed(() => {
	if (allowedDocumentTypes.value) {
		// 如果有限制，只显示允许的单据类型
		return [
			{ label: '全部', value: 'all' },
			...allDocumentTypeOptions.filter(option => 
				option.value !== 'all' && allowedDocumentTypes.value!.includes(option.value)
			)
		];
	}
	// 如果没有限制，显示所有选项
	return allDocumentTypeOptions;
});

// 响应式数据
const loading = ref(false);
const chartRef = ref<HTMLElement>();
let chartInstance: echarts.ECharts | null = null;

// 筛选表单
const currentYear = new Date().getFullYear();
const yearOptions = Array.from({ length: 5 }, (_, i) => currentYear - i);
const monthOptions = [
	{ label: '1月', value: 1 },
	{ label: '2月', value: 2 },
	{ label: '3月', value: 3 },
	{ label: '4月', value: 4 },
	{ label: '5月', value: 5 },
	{ label: '6月', value: 6 },
	{ label: '7月', value: 7 },
	{ label: '8月', value: 8 },
	{ label: '9月', value: 9 },
	{ label: '10月', value: 10 },
	{ label: '11月', value: 11 },
	{ label: '12月', value: 12 }
];

const formatDate = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;

const dateShortcuts = [
	{
		text: '最近一周',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setDate(end.getDate() - 6);
			return [start, end];
		}
	}
];

const onDateVisibleChange = (visible: boolean) => {
	if (visible && (!filterForm.dateRange || (Array.isArray(filterForm.dateRange) && filterForm.dateRange.length !== 2))) {
		const end = new Date();
		const start = new Date();
		start.setDate(end.getDate() - 6);
		filterForm.dateRange = [start, end];
	}
};

const filterForm = reactive({
	year: currentYear,
	month: new Date().getMonth() + 1,
	documentType: 'all',
	dateRange: null
});

// 监听部门变化，如果不是管理员且有限制，重置单据类型
watch([currentDeptName, allowedDocumentTypes], ([deptName, allowedTypes]) => {
	if (allowedTypes && allowedTypes.length > 0) {
		// 如果当前选择的单据类型不在允许列表中，重置为"全部"
		if (filterForm.documentType !== 'all' && !allowedTypes.includes(filterForm.documentType)) {
			filterForm.documentType = 'all';
		}
	}
});

const statistics = reactive({
	totalCount: 0,
	passedCount: 0
});

const chartData = reactive({
	dates: [] as string[],
	totalData: [] as number[],
	passedData: [] as number[]
});

// 计算日期范围
const dateRange = computed(() => {
	if (filterForm.dateRange && Array.isArray(filterForm.dateRange) && filterForm.dateRange.length === 2 && filterForm.dateRange[0] && filterForm.dateRange[1]) {
		const start = new Date(filterForm.dateRange[0]);
		const end = new Date(filterForm.dateRange[1]);
		const startDate = formatDate(start);
		const endDate = formatDate(end);
		const dates: string[] = [];
		const cur = new Date(startDate);
		const endDay = new Date(endDate);
		while (cur <= endDay) {
			dates.push(`${String(cur.getMonth() + 1).padStart(2, '0')}-${String(cur.getDate()).padStart(2, '0')}`);
			cur.setDate(cur.getDate() + 1);
		}
		return { startDate, endDate, dates };
	}
	const year = filterForm.year;
	const month = filterForm.month;
	const startDate = `${year}-${String(month).padStart(2, '0')}-01`;
	const daysInMonth = new Date(year, month, 0).getDate();
	const today = new Date();
	const isCurrentMonth = year === today.getFullYear() && month === today.getMonth() + 1;
	const maxDay = isCurrentMonth ? today.getDate() : daysInMonth;
	const endDate = `${year}-${String(month).padStart(2, '0')}-${String(maxDay).padStart(2, '0')}`;
	const dates: string[] = [];
	for (let day = 1; day <= maxDay; day++) {
		dates.push(`${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
	}
	return { startDate, endDate, dates };
});

// 获取统计数据
const fetchStatistics = async () => {
	loading.value = true;
	try {
		const { startDate, endDate } = dateRange.value;
		
		// 使用不分页的API获取所有数据
		const response = await historyDataApi.queryHistoryData({
			start_date: startDate,
			end_date: endDate
		});

		if (response && response.code === 2000) {
			// query_history_data API 返回的 data 直接是数组
			let results = Array.isArray(response.data) ? response.data : (response.data?.results || []);
			
			// 根据部门权限筛选数据（如果有限制）
			if (allowedDocumentTypes.value) {
				results = results.filter((item: any) => {
					const documentNumber = (item.code || item.document_id || item.document_number || '').toUpperCase();
					return allowedDocumentTypes.value!.some(prefix => documentNumber.startsWith(prefix));
				});
			}
			
			// 根据单据类型筛选数据
			if (filterForm.documentType !== 'all') {
				const prefix = filterForm.documentType.toUpperCase();
				results = results.filter((item: any) => {
					const documentNumber = (item.code || item.document_id || item.document_number || '').toUpperCase();
					return documentNumber.startsWith(prefix);
				});
			}
			
			// 统计总量和通过量
			statistics.totalCount = results.length;
			// 智能制证量：统计 if_pass 为 true 的记录（支持多种字段名和数据类型）
			const passedItems = results.filter((item: any) => {
				// 检查 if_pass 字段（布尔值 true 或字符串 "true"）
				const ifPass = item.if_pass === true || item.if_pass === 'true' || item.if_pass === 1 || item.if_pass === '1';
				// 检查 pass_flag 字段（布尔值 true 或字符串 "true"）
				const passFlag = item.pass_flag === true || item.pass_flag === 'true' || item.pass_flag === 1 || item.pass_flag === '1';
				return ifPass || passFlag;
			});
			statistics.passedCount = passedItems.length;
			
			// 调试信息：如果智能制证量为0但总量不为0，输出调试信息
			if (statistics.passedCount === 0 && statistics.totalCount > 0) {
				console.log('智能制证量计算调试信息：', {
					totalCount: statistics.totalCount,
					passedCount: statistics.passedCount,
					sampleItem: results[0] ? {
						if_pass: results[0].if_pass,
						pass_flag: results[0].pass_flag,
						if_pass_type: typeof results[0].if_pass,
						pass_flag_type: typeof results[0].pass_flag
					} : null
				});
			}
			
			// 处理图表数据
			processChartData(results);
		}
	} catch (error) {
		console.error('获取统计数据失败:', error);
	} finally {
		loading.value = false;
	}
};

// 处理图表数据
const processChartData = (results: any[]) => {
	const { dates } = dateRange.value;
	
	// 初始化数据数组（所有日期都初始化为0）
	const totalData: number[] = new Array(dates.length).fill(0);
	const passedData: number[] = new Array(dates.length).fill(0);
	
	// 按月统计：按日期分组
	const dataMap = new Map<string, { total: number; passed: number }>();
	
	results.forEach((item: any) => {
		if (item.push_time) {
			const date = new Date(item.push_time);
			const day = date.getDate();
			const key = `${String(date.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
			
			// 只处理在日期范围内的数据（dates 已经过滤了未来日期）
			if (dates.includes(key)) {
				if (!dataMap.has(key)) {
					dataMap.set(key, { total: 0, passed: 0 });
				}
				
				const stats = dataMap.get(key)!;
				stats.total++;
				// 检查是否通过（支持多种数据类型）
				const ifPass = item.if_pass === true || item.if_pass === 'true' || item.if_pass === 1 || item.if_pass === '1';
				const passFlag = item.pass_flag === true || item.pass_flag === 'true' || item.pass_flag === 1 || item.pass_flag === '1';
				if (ifPass || passFlag) {
					stats.passed++;
				}
			}
		}
	});
	
	// 填充数据（保留所有日期，包括没有数据的日期，数据为0）
	dates.forEach((date, index) => {
		const stats = dataMap.get(date);
		if (stats) {
			totalData[index] = stats.total;
			passedData[index] = stats.passed;
		}
		// 如果没有数据，保持为0（已经在初始化时设置了）
	});
	
	chartData.dates = dates;
	chartData.totalData = totalData;
	chartData.passedData = passedData;
	
	// 更新图表（确保图表实例已初始化）
	if (chartInstance) {
		updateChart();
	} else {
		// 如果图表还未初始化，先初始化
		nextTick(() => {
			if (chartRef.value) {
				initChart();
				updateChart();
			}
		});
	}
};

// 初始化图表
const initChart = () => {
	if (!chartRef.value) return;
	
	// 如果图表实例已存在，先销毁
	if (chartInstance) {
		chartInstance.dispose();
		chartInstance = null;
	}
	
	chartInstance = echarts.init(chartRef.value, themeConfig.value.isIsDark ? 'dark' : '');
	
	// 初始化时显示空图表
	updateChart();
	
	// 监听窗口大小变化
	window.addEventListener('resize', handleResize);
};

// 更新图表
const updateChart = () => {
	if (!chartInstance) return;
	
	const option = {
		backgroundColor: 'transparent',
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross'
			}
				},
				legend: {
			data: ['单据总量', '智能制证量'],
			right: 20,
			top: 10,
					textStyle: {
				color: themeConfig.value.isIsDark ? '#dadada' : '#303133'
			}
		},
		grid: {
			top: 60,
			right: 30,
			bottom: 30,
			left: 50
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: chartData.dates.length > 0 ? chartData.dates : ['暂无数据'],
			axisLabel: {
				color: themeConfig.value.isIsDark ? '#dadada' : '#303133'
			}
		},
		yAxis: {
			type: 'value',
			axisLabel: {
				color: themeConfig.value.isIsDark ? '#dadada' : '#303133'
			},
			splitLine: {
				lineStyle: {
					type: 'dashed',
					color: themeConfig.value.isIsDark ? '#3a3a3a' : '#f0f0f0'
				}
			}
				},
				series: [
					{
				name: '单据总量',
						type: 'line',
						smooth: true,
				symbol: 'circle',
				symbolSize: 6,
				data: chartData.totalData.length > 0 ? chartData.totalData : [0],
				lineStyle: {
					color: '#007aff',
					width: 2
				},
				itemStyle: {
					color: '#007aff'
				},
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: 'rgba(0, 122, 255, 0.3)' },
						{ offset: 1, color: 'rgba(0, 122, 255, 0.05)' }
					])
				}
			},
			{
				name: '智能制证量',
						type: 'line',
						smooth: true,
				symbol: 'circle',
				symbolSize: 6,
				data: chartData.passedData.length > 0 ? chartData.passedData : [0],
				lineStyle: {
					color: '#34c759',
					width: 2
						},
						itemStyle: {
					color: '#34c759'
				},
				areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: 'rgba(52, 199, 89, 0.3)' },
						{ offset: 1, color: 'rgba(52, 199, 89, 0.05)' }
					])
				}
			}
		]
	};
	
	chartInstance.setOption(option, true); // 使用 notMerge 模式，完全替换配置
	
	// 确保图表正确渲染
			nextTick(() => {
		if (chartInstance) {
			chartInstance.resize();
				}
			});
		};

// 处理窗口大小变化
const handleResize = () => {
	if (chartInstance) {
		chartInstance.resize();
	}
};

// 筛选变化处理
const handleFilterChange = () => {
	fetchStatistics();
};

// 监听主题变化
		watch(
	() => themeConfig.value.isIsDark,
			() => {
		nextTick(() => {
			if (chartInstance) {
				chartInstance.dispose();
				initChart();
			}
		});
	}
);

// 生命周期
onMounted(() => {
				nextTick(() => {
		// 确保 DOM 完全渲染后再初始化图表
					setTimeout(() => {
			initChart();
			fetchStatistics();
		}, 100);
	});
});

onBeforeUnmount(() => {
	if (chartInstance) {
		chartInstance.dispose();
	}
	window.removeEventListener('resize', handleResize);
});
</script>

<style scoped lang="scss">
.home-container {
	padding: 24px;
	background: #f5f5f7;
	min-height: calc(100vh - 80px);
}

.filter-section {
	background: #ffffff;
	border-radius: 18px;
	padding: 20px 24px;
	margin-bottom: 24px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.02);
	border: 1px solid rgba(0, 0, 0, 0.06);
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 32px;
	flex-wrap: wrap;
}

.filter-group {
	display: flex;
	align-items: center;
	gap: 8px;
	flex-shrink: 0;
}

.filter-separator {
	color: #86868b;
	font-size: 1rem;
	padding: 0 4px;
	user-select: none;
}

.filter-select {
	flex-shrink: 0;
}

.stats-section {
	display: flex;
	gap: 16px;
	flex: 1;
	justify-content: flex-end;
	min-width: 0;
	align-items: center;
}

.stat-card {
	background: linear-gradient(135deg, rgba(0, 122, 255, 0.05) 0%, rgba(0, 122, 255, 0.02) 100%);
	border-radius: 12px;
	padding: 16px 20px;
	display: flex;
	align-items: center;
	gap: 12px;
	border: 1px solid rgba(0, 122, 255, 0.1);
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	flex: 0 0 auto;
	min-width: 140px;
	height: 64px;
	box-sizing: border-box;
}

.stat-card:nth-child(2) {
	background: linear-gradient(135deg, rgba(52, 199, 89, 0.05) 0%, rgba(52, 199, 89, 0.02) 100%);
	border-color: rgba(52, 199, 89, 0.1);
}

.stat-card:hover {
	transform: translateY(-1px);
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
	border-color: rgba(0, 122, 255, 0.2);
}

.stat-card:nth-child(2):hover {
	border-color: rgba(52, 199, 89, 0.2);
}

.stat-icon {
	width: 40px;
	height: 40px;
	border-radius: 10px;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.stat-content {
	flex: 1;
	min-width: 0;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.stat-value {
	font-size: 1.5rem;
	font-weight: 600;
	color: #1d1d1f;
	line-height: 1.2;
	margin-bottom: 2px;
	letter-spacing: -0.3px;
	white-space: nowrap;
}

.stat-label {
	font-size: 0.8125rem;
	color: #86868b;
	font-weight: 400;
	line-height: 1.2;
	white-space: nowrap;
}

.chart-section {
	background: #ffffff;
	border-radius: 18px;
	padding: 32px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.02);
	border: 1px solid rgba(0, 0, 0, 0.06);
}

.chart-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24px;
}

.chart-header h3 {
	font-size: 1.5rem;
	font-weight: 600;
	color: #1d1d1f;
	margin: 0;
	letter-spacing: -0.3px;
}

.view-toggle {
	display: flex;
	gap: 8px;
}

.chart-container {
	width: 100%;
			height: 400px;
}

.chart {
			width: 100%;
				height: 100%;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-select) {
	width: 140px;
}

:deep(.el-date-editor.el-date-editor--daterange) {
	width: 280px;
}

:deep(.el-select .el-input__wrapper) {
	border-radius: 8px;
	border: 1px solid rgba(0, 0, 0, 0.12);
	transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
	height: 36px;
	padding: 0 12px;
}

:deep(.el-select .el-input__wrapper:hover) {
	border-color: rgba(0, 0, 0, 0.2);
}

:deep(.el-select .el-input__wrapper.is-focus) {
	border-color: #007aff;
	box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
}

:deep(.el-input__inner) {
	font-size: 0.9375rem;
	height: 36px;
	line-height: 36px;
}

:deep(.el-button-group .el-button) {
	border-radius: 10px;
	font-weight: 500;
	transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.el-button-group .el-button--primary) {
	background: #007aff;
	border-color: #007aff;
	color: #ffffff;
}

:deep(.el-button-group .el-button:not(.el-button--primary)) {
	background: #f8f9fa;
	border-color: rgba(0, 0, 0, 0.1);
	color: #86868b;
}

:deep(.el-button-group .el-button:not(.el-button--primary):hover) {
	color: #1d1d1f;
	background: rgba(0, 0, 0, 0.04);
}

@media (max-width: 1200px) {
	.filter-section {
		flex-direction: column;
		align-items: stretch;
		gap: 20px;
	}

	.stats-section {
		width: 100%;
		justify-content: flex-start;
	}

	.stat-card {
		flex: 1;
		min-width: 0;
	}
}

@media (max-width: 768px) {
	.home-container {
		padding: 16px;
	}

	.filter-section {
		padding: 16px;
		gap: 16px;
	}

	.filter-group {
		width: 100%;
		flex-wrap: wrap;
	}

	.filter-select {
		flex: 1;
		min-width: 140px;
	}

	:deep(.el-select) {
		width: 100%;
	}

	.stats-section {
		flex-direction: column;
		width: 100%;
		gap: 12px;
	}

	.stat-card {
		width: 100%;
		min-width: 0;
		height: auto;
		padding: 16px;
	}

	.chart-header {
		flex-direction: column;
		align-items: flex-start;
		gap: 16px;
	}

	.chart-container {
		height: 300px;
	}
}
</style>
